from PyQt6.QtWidgets import (
    QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QListWidget, QListWidgetItem,
    QSpinBox, QMessageBox, QDialog,QTextEdit
)
from PyQt6.QtCore import Qt  # 正确导入 Qt
from utils.communication import send_request
from ui.dialogs import show_info, show_error


class UserWindow(QWidget):
    def __init__(self, username, main_window=None):
        super().__init__()
        self.main_window = main_window  # 保存主界面引用，方便返回
        self.username = username
        self.setWindowTitle(f"用户界面 - {username}")
        self.resize(500, 400)

        # 初始化控件
        self.dish_list_widget = QListWidget()
        self.cart = {}  # key: dish id, value: dict{name, price, quantity}

        self.btn_refresh = QPushButton("刷新菜品列表")
        self.btn_view_cart = QPushButton("查看购物车")
        self.btn_checkout = QPushButton("提交订单")
        self.btn_check_history = QPushButton("查询历史订单")
        self.btn_back = QPushButton("返回主页面")

        # 创建主布局（垂直布局）
        layout = QVBoxLayout()
        layout.addWidget(QLabel(f"欢迎，{username}"))
        layout.addWidget(self.dish_list_widget)

        # 添加按钮区域
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(self.btn_refresh)
        btn_layout.addWidget(self.btn_view_cart)
        btn_layout.addWidget(self.btn_checkout)
        btn_layout.addWidget(self.btn_back)

        # 查询历史订单按钮
        layout.addWidget(self.btn_check_history)

        # 加入按钮横向布局
        layout.addLayout(btn_layout)

        # 历史订单显示区域
        self.order_display = QTextEdit()
        self.order_display.setReadOnly(True)
        layout.addWidget(self.order_display)

        # 应用主布局
        self.setLayout(layout)

        # 信号绑定
        self.btn_refresh.clicked.connect(self.load_dishes)
        self.btn_view_cart.clicked.connect(self.view_cart)
        self.btn_checkout.clicked.connect(self.checkout)
        self.dish_list_widget.itemDoubleClicked.connect(self.handle_dish_double_click)
        self.btn_back.clicked.connect(self.back_to_main)
        self.btn_check_history.clicked.connect(self.check_user_orders)

        # 初始加载菜品
        self.load_dishes()

    def load_dishes(self):
        # 请求后端获取菜品列表
        #创建字典，写入对应指令
        request_data = {"action": "getDishes"}
        #发送对应指令并等待返回
        response = send_request(request_data)
        self.dish_list_widget.clear()
        #若超时返回None
        if response is None:
            show_error(self, "错误", "服务器无响应，无法加载菜品")
            return
        #若得到菜单列表，获取dishes键对应值，默认值[],防止出错
        dishes = response.get("dishes", [])
        #遍历dishes每一个dish,每一个dish都是一个字典
        for dish in dishes:
            # 将每一个dish字典的键值对拼接，格式化显示
            item = QListWidgetItem(f"{dish['name']} ￥{dish['price']:.2f}")
            #给这个 item 附加自定义数据，绑定完整的菜品字典。
            # 1000 是自定义角色编号（用作标识，避免与 Qt 内置角色冲突）
            item.setData(1000, dish)
            #将创建好的 item 添加到界面上的菜品列表控件中，供用户选择。
            self.dish_list_widget.addItem(item)

    def handle_dish_double_click(self, item):
        # 双击列表项添加到购物车
        dish = item.data(1000)
        self.add_to_cart_dialog(dish)

    def view_cart(self):
        # 显示购物车内容，弹窗列表
        if not self.cart:
            show_info(self, "购物车", "购物车为空")
            return

        msg = ""
        total = 0.0
        for dish_id, info in self.cart.items():
            subtotal = info['price'] * info['quantity']
            msg += f"{info['name']} x {info['quantity']} = ￥{subtotal:.2f}\n"
            total += subtotal
        msg += f"\n总计: ￥{total:.2f}"
        show_info(self, "购物车内容", msg)

    def checkout(self):
        # 提交订单到后端
        if not self.cart:
            show_error(self, "错误", "购物车为空，无法下单")
            return

        items = []
        for dish_id, info in self.cart.items():
            items.append({
                "dishId": dish_id,
                "quantity": info['quantity']
            })

        request_data = {
            "action": "addOrder",
            "username": self.username,
            "items": items
        }
        response = send_request(request_data)
        if response is None:
            show_error(self, "错误", "服务器无响应，无法提交订单")
            return

        if response.get("result") is True:
            show_info(self, "成功", "订单提交成功")
            self.cart.clear()
        else:
            show_error(self, "失败", "订单提交失败")

    def add_to_cart_dialog(self, dish):
        # 弹出输入数量对话框
        class AddDialog(QDialog):
            def __init__(self, parent=None):
                super().__init__(parent)
                self.setWindowTitle(f"添加到购物车 - {dish['name']}")
                self.resize(250, 100)

                self.spin = QSpinBox()
                self.spin.setMinimum(1)
                self.spin.setMaximum(99)
                self.spin.setValue(1)

                btn_ok = QPushButton("确定")
                btn_cancel = QPushButton("取消")

                btn_ok.clicked.connect(self.accept)
                btn_cancel.clicked.connect(self.reject)

                layout = QVBoxLayout()
                layout.addWidget(QLabel("请选择数量："))
                layout.addWidget(self.spin)

                btn_layout = QHBoxLayout()
                btn_layout.addWidget(btn_ok)
                btn_layout.addWidget(btn_cancel)
                layout.addLayout(btn_layout)

                self.setLayout(layout)

        dlg = AddDialog(self)
        if dlg.exec():
            qty = dlg.spin.value()
            dish_id = dish['id']
            if dish_id in self.cart:
                self.cart[dish_id]['quantity'] += qty
            else:
                self.cart[dish_id] = {
                    "name": dish['name'],
                    "price": dish['price'],
                    "quantity": qty
                }
            show_info(self, "成功", f"已将 {dish['name']} x{qty} 添加到购物车")
    def back_to_main(self):
        if self.main_window:
            self.main_window.show()  # 重新显示主界面
        self.close()  # 关闭当前窗口
    def check_user_orders(self):
        request = {"action": "getOrders"}
        response = send_request(request)
        self.order_display.clear()

        if response is None:
            show_error(self, "错误", "服务器无响应，无法加载订单")
            return

        orders = response.get("orders", [])
        current_user = self.username
        matched_orders = [o for o in orders if o.get("username") == current_user]

        if not matched_orders:
            self.order_display.setText("暂无历史订单。")
            return

        display_text = ""
        for order in matched_orders:
            status = "已完成（待取餐）" if order.get("status") == "done" else "未完成"
            items = order.get("items", [])
            items_text = ", ".join(f"{item['dishName']} x{item['quantity']}" for item in items)
            display_text += (
                f"订单ID: {order['id']}\n"
                f"状态: {status}\n"
                f"菜品: {items_text}\n"
                f"{'-'*30}\n"
            )

        self.order_display.setText(display_text)
